package org.fast.develop.logicflow.ws;

import lombok.extern.slf4j.Slf4j;
import org.fast.develop.logicflow.LogicFlowManagementConfiguration;
import org.fast.develop.logicflow.ws.manager.WsSessionManager;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 * WebSocket通讯编辑服务
 *
 * @author Administrator
 */
@ServerEndpoint("/ws")
@Slf4j
public class LogicFlowServerEndpoint {



    private static LogicDebugService logicDebugService;
    private static WsSessionManager wsSessionManager;
    private static LogicFlowManagementConfiguration logicFlowManagementConfiguration;

    public LogicFlowServerEndpoint() {
    }

    public LogicFlowServerEndpoint(LogicFlowManagementConfiguration logicFlowManagementConfiguration) {
        this.logicFlowManagementConfiguration = logicFlowManagementConfiguration;
        this.wsSessionManager = logicFlowManagementConfiguration.getWsSessionManager();
        this.logicDebugService = logicFlowManagementConfiguration.getLogicDebugService();
    }

    @OnOpen
    public void onOpen(Session session) {
        log.info("【有新的客户端连接了】：{}", session.getId());
        //将新用户加入在线组
        wsSessionManager.getWsSessionStore().put(session.getId(), session);
        log.info("【websocket消息】有新的连接，总数：{}", wsSessionManager.getWsSessionStore().getSessions().size());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("【websocket消息】收到客户端发来的消息：{}", message);
        logicDebugService.run(session.getId(), message);
        //-cc
//        wsSessionManager.getWebSockeLauncher().sendMsg(session.getId(), message);
    }

    @OnClose
    public void onClose(Session session) {
        wsSessionManager.getWsSessionStore().remove(session.getId());
        log.info("【websocket消息】连接断开，总数：{}", wsSessionManager.getWsSessionStore().getSessions().size());
    }

}
